﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Thinker.SignChannel.Dto;
using Thinker.SignChannel.Entities;
using Thinker.SignChannel.Excels;
using Thinker.SignChannel.Repositories;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Content;
using Volo.Abp.Threading;

namespace Thinker.SignChannel.Records;

public class RecordAppService(
    IRecordRepository recordRepository,
    LocalizedExcelAccessor excelAccessor,
    RecordManager recordManager) :
    SignChannelAppService, IRecordAppService
{
    public async Task<IRemoteStreamContent> ExportAsync(Guid timeId)
    {
        var records = await recordRepository.GetListAsync(e => e.TimeId == timeId);
        var list = records.Select(MapToExcelDto).ToList();
        return excelAccessor.CreateStream(list, "考勤记录");
    }

    public async Task<IRemoteStreamContent> ExportAllAsync()
    {
        var records = await recordRepository.GetListAsync();
        var list = records.Select(MapToExcelDto).ToList();
        return excelAccessor.CreateStream(list, "考勤记录");
    }

    public async Task<PagedResultDto<SignRecordDto>> GetListAsync(RecordListInput input)
    {
        var records = await recordRepository.GetQueryableAsync();
        records = records.Where(r => r.TimeId == input.TimeId);

        records = records.OrderBy(r => r.RecordTime);
        records = records.PageBy(input);
        var list = await AsyncExecuter.ToListAsync(records);

        var items = list.Select(MapToDto).ToList();
        return new PagedResultDto<SignRecordDto>(list.Count, items);
    }

    private SignRecordDto MapToDto(Record record)
    {
        return AsyncHelper.RunSync(() => MapToDtoAsync(record));
    }

    private async Task<SignRecordDto> MapToDtoAsync(Record record)
    {
        var info = await recordManager.GetAsync(record);
        return info.ToSignRecordDto(ObjectMapper);
    }

    private async Task<RecordExcelDto> MapToExcelDtoAsync(Record record)
    {
        var info = await recordManager.GetAsync(record);
        return RecordExcelDto.From(info, L);
    }

    private RecordExcelDto MapToExcelDto(Record record)
    {
        return AsyncHelper.RunSync(() => MapToExcelDtoAsync(record));
    }
}